package threadpool;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 *Description:线程池讲解
 *Version:1.0.0
 *@author shihb
 *@date 2020/5/24 19:42
 */
public class ExecutorsDemo {

  public static void main(String[] args) {
    /**
     * ExecutorService pool = Executors.newSingleThreadExecutor();
     *  只有一个线程
     *  public static ExecutorService newSingleThreadExecutor() {
     *      return new FinalizableDelegatedExecutorService
     *          (new ThreadPoolExecutor(1, 1,0L, TimeUnit.MILLISECONDS,new LinkedBlockingQueue<Runnable>()));
     *  }
     *  ExecutorService pool = Executors.newFixedThreadPool(5);
     *  固定线程池的大小
     *  public static ExecutorService newFixedThreadPool(int nThreads) {
     *      return new ThreadPoolExecutor
     *      (nThreads, nThreads, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>());
     *  }
     *  ExecutorService pool = Executors.newCachedThreadPool();
     *  弹性的线程池，尽量多的创建
     *  public static ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
     *      return new ThreadPoolExecutor
     *      (0, Integer.MAX_VALUE, 60L, TimeUnit.SECONDS,new SynchronousQueue<Runnable>(),threadFactory);
     *  }
     *  底层都是
     *  public ThreadPoolExecutor(int corePoolSize, //核心线程池数量
     *                           int maximumPoolSize,//最大线程池数量
     *                           long keepAliveTime,//超时等待时间
     *                           TimeUnit unit,// 时间单位
     *                           BlockingQueue<Runnable> workQueue,//缓冲队列
     *                           ThreadFactory threadFactory,// 线程工厂
     *                           RejectedExecutionHandler handler//拒绝策略) {
     *  拒绝策略：
     *  ThreadPoolExecutor.AbortPolicy() 抛异常 默认的拒绝策略
     *  ThreadPoolExecutor.CallerRunsPolicy()  哪来的回哪里去
     *  ThreadPoolExecutor.DiscardOldestPolicy() 尝试竞争，不成功丢任务
     *  ThreadPoolExecutor.DiscardPolicy() 丢任务
     */


    // 手动创建线程池，推荐
    ThreadPoolExecutor pool = new ThreadPoolExecutor(2,
        //cpu逻辑核数
        Runtime.getRuntime().availableProcessors(),
        3,
        TimeUnit.SECONDS,
        new LinkedBlockingDeque<>(3),
        Executors.defaultThreadFactory(),
        new ThreadPoolExecutor.DiscardPolicy());

    try {
      for (int i = 0; i < 10; i++) {
        pool.execute(()->{
          System.out.println(Thread.currentThread().getName());
        });
      }
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      pool.shutdown();
    }
  }
}
